//
//  WebViewController.m
//  FreeTrip
//
//  Created by dlios on 15/8/19.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "WebViewController.h"

#import "DataBaseHandle.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKExtension/SSEShareHelper.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKUI/SSUIShareActionSheetStyle.h>
#import <ShareSDKUI/SSUIShareActionSheetCustomItem.h>
#import <ShareSDK/ShareSDK+Base.h>

@interface WebViewController ()<UIWebViewDelegate>


/**
 *  面板
 */
@property (nonatomic, strong) UIView *panelView;

/**
 *  加载视图
 */
@property (nonatomic, strong) UIActivityIndicatorView *loadingView;

@property (nonatomic, assign) BOOL isSecondEnter;

@property (nonatomic, retain) MBProgressHUD *HUD;


@end

@implementation WebViewController

- (void)dealloc
{
    [_panelView release];
    [_loadingView release];
    [_viewTitle release];
    [_viewType release];
    [_viewUrl release];
    [_webView release];
    [super dealloc];
    
}
- (void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    
    AppDelegate *dele = [[UIApplication sharedApplication]delegate];
    if (dele.isNight == 1) {
       
        self.view.backgroundColor = [UIColor lightGrayColor];
        
        self.webView.backgroundColor = [UIColor lightGrayColor];
        self.webView.scrollView.alpha = 0.7;
        
        self.webView.opaque = NO;
    }
    else{
        
        
        self.view.backgroundColor = [UIColor whiteColor];
        self.webView.opaque = YES;
        self.webView.scrollView.alpha = 1;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.backgroundColor = [UIColor colorWithRed:0.613 green:0.914 blue:1.000 alpha:1.000];
    

    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.viewUrl]];
    
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, -99 * SAHeight, 375 * SAWindth, 667 * SAHeight)];
    if ([self.weiXun isEqualToString:@"WeiXun"])
    {
        self.webView.frame = CGRectMake(0, -150 * SAHeight, 375 * SAWindth, 710 * SAHeight);
    }
    /* webView取消回弹效果 */
    self.webView.scrollView.bounces = NO;

    self.navigationController.navigationBarHidden = NO;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self.view addSubview:self.webView];
    [self.webView loadRequest:request];
    self.webView.delegate = self;
    [self.webView release];
    
    self.title = self.viewTitle;
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    self.HUD.labelText = @"Loading";
    self.HUD.labelFont = [UIFont boldSystemFontOfSize:20];
    self.HUD.labelColor = [UIColor orangeColor];
    [self.HUD show:YES];
    self.HUD.backgroundColor  = [UIColor darkGrayColor];
    self.HUD.dimBackground = YES;
    [self.view addSubview:self.HUD];
    [self.HUD release];
    
    /* 收藏按钮 */
    UIButton *likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    likeButton.frame = CGRectMake(0, 0, 32 * SAWindth, 32 * SAHeight);
    
    [likeButton setImage:[UIImage imageNamed:@"likeOff.png"] forState:UIControlStateNormal];
    [likeButton setImage:[UIImage imageNamed:@"like.png"] forState:UIControlStateSelected];
    
    if ([[DataBaseHandle shareDataBaseHandle] selectViewWithTitle:self.title]) {
        
        
        likeButton.selected = YES;
    }
    else
    {
        likeButton.selected = NO;
    }
    [likeButton addTarget:self action:@selector(likeClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    /* 分享按钮 */
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    shareButton.frame = CGRectMake(32 * SAWindth, 0, 32 * SAWindth, 32 *SAHeight);
    [shareButton setImage:[UIImage imageNamed:@"fenxiang.png"] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(showShareActionSheet:) forControlEvents:UIControlEventTouchUpInside];
    
    /* 按钮view */
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 64 * SAWindth, 32 * SAHeight)];
    [rightView addSubview:likeButton];
    [rightView addSubview:shareButton];
    
    /* rightBar */
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithCustomView:rightView];
    
    self.navigationItem.rightBarButtonItem = rightBar;
    
}

#pragma mark - webview 协议
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
    
    if(!self.isSecondEnter)
    {
//        self.isSecondEnter = !self.isSecondEnter;
        
        [self.HUD hide:YES afterDelay:2];

        return YES;
    }
    else
    {
        return NO;
        
    }

   
    
}



#pragma mark 显示分享菜单

/**
 *  显示分享菜单
 *
 *  @param view 容器视图
 */
- (void)showShareActionSheet:(UIButton *)view
{
    /**
     * 在简单分享中，只要设置共有分享参数即可分享到任意的社交平台
     **/
    WebViewController *theController = self;
    
    //1、创建分享参数（必要）
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    NSArray* imageArray = @[self.viewTitle];
    [shareParams SSDKSetupShareParamsByText:self.viewUrl
                                     images:imageArray
                                        url:[NSURL URLWithString:@"http://mob.com"]
                                      title:self.viewTitle
                                       type:SSDKContentTypeAuto];
    
    //1.2、自定义分享平台（非必要）
//    NSMutableArray *activePlatforms = [NSMutableArray arrayWithArray:[ShareSDK activePlatforms]];
//    //添加一个自定义的平台（非必要）
//    SSUIShareActionSheetCustomItem *item = [SSUIShareActionSheetCustomItem itemWithIcon:[UIImage imageNamed:@"Icon.png"]
//                                                                                  label:@"自定义"
//                                                                                onClick:^{
//                                                                                    
//                                                                                    //自定义item被点击的处理逻辑
//                                                                                    NSLog(@"=== 自定义item被点击 ===");
//                                                                                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"自定义item被点击"
//                                                                                                                                        message:nil
//                                                                                                                                       delegate:nil
//                                                                                                                              cancelButtonTitle:@"确定"
//                                                                                                                              otherButtonTitles:nil];
//                                                                                    [alertView show];
//                                                                                }];
//    [activePlatforms addObject:item];
//    
    //设置分享菜单栏样式（非必要）
    //        [SSUIShareActionSheetStyle setActionSheetBackgroundColor:[UIColor colorWithRed:249/255.0 green:0/255.0 blue:12/255.0 alpha:0.5]];
    //        [SSUIShareActionSheetStyle setActionSheetColor:[UIColor colorWithRed:21.0/255.0 green:21.0/255.0 blue:21.0/255.0 alpha:1.0]];
    //        [SSUIShareActionSheetStyle setCancelButtonBackgroundColor:[UIColor colorWithRed:21.0/255.0 green:21.0/255.0 blue:21.0/255.0 alpha:1.0]];
    //        [SSUIShareActionSheetStyle setCancelButtonLabelColor:[UIColor whiteColor]];
    //        [SSUIShareActionSheetStyle setItemNameColor:[UIColor whiteColor]];
    //        [SSUIShareActionSheetStyle setItemNameFont:[UIFont systemFontOfSize:10]];
    //        [SSUIShareActionSheetStyle setCurrentPageIndicatorTintColor:[UIColor colorWithRed:156/255.0 green:156/255.0 blue:156/255.0 alpha:1.0]];
    //        [SSUIShareActionSheetStyle setPageIndicatorTintColor:[UIColor colorWithRed:62/255.0 green:62/255.0 blue:62/255.0 alpha:1.0]];
    
    //2、分享
    [ShareSDK showShareActionSheet:view
                             items:nil
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   
                   switch (state) {
                           
                       case SSDKResponseStateBegin:
                       {
                           [theController showLoadingView:YES];
                           break;
                       }
                       case SSDKResponseStateSuccess:
                       {
//                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
//                                                                               message:nil
//                                                                              delegate:nil
//                                                                     cancelButtonTitle:@"确定"
//                                                                     otherButtonTitles:nil];
//                           [alertView show];
                           
                           
                           UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"分享成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
                           UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                               
                           }];
                           [alert addAction:action];
                           [self presentViewController:alert animated:YES completion:^{
                               
                           }];
                           
                           
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
//                           if (platformType == SSDKPlatformTypeSMS && [error code] == 201)
//                           {
//                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
//                                                                               message:@"失败原因可能是：1、短信应用没有设置帐号；2、设备不支持短信应用；3、短信应用在iOS 7以上才能发送带附件的短信。"
//                                                                              delegate:nil
//                                                                     cancelButtonTitle:@"OK"
//                                                                     otherButtonTitles:nil, nil];
//                               [alert show];
//                               break;
//                           }
//                           else if(platformType == SSDKPlatformTypeMail && [error code] == 201)
//                           {
//                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
//                                                                               message:@"失败原因可能是：1、邮件应用没有设置帐号；2、设备不支持邮件应用；"
//                                                                              delegate:nil
//                                                                     cancelButtonTitle:@"OK"
//                                                                     otherButtonTitles:nil, nil];
//                               [alert show];
//                               break;
//                           }
//                           else
//                           {
//                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
//                                                                               message:[NSString stringWithFormat:@"%@",error]
//                                                                              delegate:nil
//                                                                     cancelButtonTitle:@"OK"
//                                                                     otherButtonTitles:nil, nil];
//                               [alert show];
//                               break;
//                           }
                           break;
                       }
                       case SSDKResponseStateCancel:
                       {
//                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
//                                                                               message:nil
//                                                                              delegate:nil
//                                                                     cancelButtonTitle:@"确定"
//                                                                     otherButtonTitles:nil];
//                           [alertView show];
                           
                           UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"分享已取消" message:nil preferredStyle:UIAlertControllerStyleAlert];
                           UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                               
                           }];
                           [alert addAction:action];
                           [self presentViewController:alert animated:YES completion:^{
                               
                           }];
                           
                           
                           
                           
                           break;
                       }
                       default:
                           break;
                   }
                   
                   if (state != SSDKResponseStateBegin)
                   {
                       [theController showLoadingView:NO];
                   }
                   
               }];
    
    //另附：设置跳过分享编辑页面，直接分享的平台。
    //        SSUIShareActionSheetController *sheet = [ShareSDK showShareActionSheet:view
    //                                                                         items:nil
    //                                                                   shareParams:shareParams
    //                                                           onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
    //                                                           }];
    //
    //        //删除和添加平台示例
    //        [sheet.directSharePlatforms removeObject:@(SSDKPlatformTypeWechat)];
    //        [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSinaWeibo)];
}

#pragma mark -

/**
 *  显示加载动画
 *
 *  @param flag YES 显示，NO 不显示
 */
- (void)showLoadingView:(BOOL)flag
{
    if (flag)
    {
        [self.view addSubview:self.panelView];
        [self.loadingView startAnimating];
    }
    else
    {
        [self.panelView removeFromSuperview];
    }
}


#pragma mark - 收藏点击事件
- (void)likeClicked:(UIButton *)button
{
    
    button.selected = !button.selected;
    if (button.selected) {
        NSDictionary *dic = [[NSDictionary alloc] initWithObjects:@[self.viewTitle,self.viewUrl,self.viewType] forKeys:@[@"title",@"url",@"type"]];
        [[DataBaseHandle shareDataBaseHandle] insertView:dic];

    }
    else
    {

        [[DataBaseHandle shareDataBaseHandle] deleteView:self.title];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
